package argo.hot100.tree;

public class MaxPathSum {

    int maxsum = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        maxGain(root);
        return maxsum;
    }

    int maxGain(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int leftMax = Math.max(maxGain(root.left), 0);
        int rightMax = Math.max(maxGain(root.right), 0);

        int currGain = leftMax + rightMax + root.val;
        maxsum = Math.max(currGain, maxsum);

        return root.val + Math.max(leftMax, rightMax);

    }


}
